package com.example.myapplication.geofence

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.JobIntentService
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import com.example.myapplication.BuildConfig
import com.example.myapplication.MapsActivity
import com.example.myapplication.R
import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofenceStatusCodes
import com.google.android.gms.location.GeofencingEvent


class GeofenceJobIntentService : JobIntentService() {
    private val TAG = GeofenceJobIntentService::class.java.simpleName

    override fun onHandleWork(intent: Intent) {
        setData(intent, applicationContext)
    }

    /**
     * do your work
     */
    private fun setData(intent: Intent?, context: Context?) {
        val geofencingEvent = GeofencingEvent.fromIntent(intent)
        if (geofencingEvent.hasError()) {
            val errorMessage = GeofenceStatusCodes
                .getStatusCodeString(geofencingEvent.errorCode)
            Log.e(TAG, "error $errorMessage")
            return
        }

        val geofenceTransition = geofencingEvent.geofenceTransition

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT
        ) {

            val triggeringGeofences = geofencingEvent.triggeringGeofences

            var type = when {
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER -> "ENTER"
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL -> "DWELL"
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT -> "EXIT"
                else -> "Unknown Transition"
            }

            for (item in triggeringGeofences) {
                sendNotification(
                    context,
                    "Hi you $type  size = ${triggeringGeofences.size} -${item.requestId} latitude:${geofencingEvent.triggeringLocation.latitude} \n longitude:${geofencingEvent.triggeringLocation.longitude}"
                )
                Log.i(TAG, "success $type ${triggeringGeofences[0].requestId}")
            }
        } else {
            Log.e(TAG, "error $geofenceTransition")
        }
    }

    private fun sendNotification(context: Context?, notificationDetails: String) {
        val mNotificationManager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name: CharSequence = context?.getString(R.string.app_name)
            val mChannel = NotificationChannel(
                CHANNEL_ID,
                name,
                NotificationManager.IMPORTANCE_DEFAULT
            )

            mNotificationManager.createNotificationChannel(mChannel)
        }

        val notificationIntent = Intent(context, MapsActivity::class.java)

        val stackBuilder = TaskStackBuilder.create(context)

        stackBuilder.addParentStack(MapsActivity::class.java)

        stackBuilder.addNextIntent(notificationIntent)

        val notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE)

        val builder = NotificationCompat.Builder(context)

        builder.setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.mipmap.ic_launcher
                )
            )
            .setColor(Color.RED)
            .setContentTitle("Geofence")
            .setContentText(notificationDetails)
            .setContentIntent(notificationPendingIntent)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setChannelId(CHANNEL_ID)
        }

        builder.setAutoCancel(true)

        mNotificationManager.notify((System.currentTimeMillis() % 10000).toInt(), builder.build())
    }


    companion object {
        private const val JOB_ID = 573
        private const val CHANNEL_ID = BuildConfig.APPLICATION_ID

        /**
         * Convenience method for enqueuing work in to this service.
         */
        fun enqueueWork(context: Context?, intent: Intent?) {
            enqueueWork(context!!, GeofenceJobIntentService::class.java, JOB_ID, intent!!)
        }
    }
}